<template>
  <div class="body" v-if="!initLoading">
    <div class="goods-detail">
      <image :src="orderGoodsDetail.goods_image" mode="aspectFill"></image>
      <div class="goods-detail-right">
        <div class="goods-name">
          {{ orderGoodsDetail.goods_name }}
        </div>
        <div class="goods-name-bottom">
          <div class="goods-sku">{{ orderGoodsDetail.sku_attr_text }}</div>
          <div class="goods-num">x{{ orderGoodsDetail.total_num }}</div>
        </div>
      </div>
    </div>
    <!--  -->
    <div class="cell-main">
      <div class="cell-title">服务类型</div>
      <div class="service-list">
        <div
          class="service-item"
          :class="formData.type == 1 ? 'active' : ''"
          :style="[
            `background:${formData.type == 1 ? DIYTHEME?.deputy_bg : ''}`,
            `color:${formData.type == 1 ? DIYTHEME?.deputy_color : ''}`,
          ]"
          @click="onSelectedType(1)"
        >
          退货退款
        </div>
        <div
          class="service-item"
          :class="formData.type == 2 ? 'active' : ''"
          :style="[
            `background:${formData.type == 2 ? DIYTHEME?.deputy_bg : ''}`,
            `color:${formData.type == 2 ? DIYTHEME?.deputy_color : ''}`,
          ]"
          @click="onSelectedType(2)"
        >
          换货
        </div>
        <div
          class="service-item"
          :class="formData.type == 3 ? 'active' : ''"
          :style="[
            `background:${formData.type == 3 ? DIYTHEME?.deputy_bg : ''}`,
            `color:${formData.type == 3 ? DIYTHEME?.deputy_color : ''}`,
          ]"
          @click="onSelectedType(3)"
        >
          仅退款
        </div>
      </div>
    </div>

    <!--  -->
    <div class="cell-main flex between items-center">
      <div class="cell-title">申请原因</div>
      <div class="reason flex items-center">
        <picker
          mode="selector"
          @change="onReasonChange"
          :range="reasonList"
          :value="formData.type_desc"
        >
          <div v-if="reasonIndex > -1">
            {{ formData.type_desc }}
          </div>
          <div v-else class="">请选择</div>
        </picker>
        <div class="text-grey fz-small icon icon-yao-1"></div>
      </div>
    </div>

    <!--  -->
    <div class="cell-main">
      <div class="cell-title">申请说明</div>
      <div class="reason">
        <textarea
          maxlength="2000"
          placeholder="请详细填写申请说明，注意保持商品的完好，建议您先与平台沟通"
          v-model="formData.content"
        ></textarea>
      </div>
    </div>

    <!-- 退款金额 -->
    <template v-if="formData.type != 2">
      <div class="cell-main">
        <div class="rocellw-title">退款金额</div>
        <div class="mt10">
          <money :value="orderGoodsDetail.total_pay_price"></money>
        </div>
      </div>
    </template>

    <!-- 上传图片 -->
    <div class="cell-main">
      <div class="cell-title">上传凭证 (最多5张)</div>
      <div>
        <uploadList :max-count="5" @change="uploadChange"></uploadList>
      </div>
    </div>

    <div class="bottom-fixed">
      <hover>
        <div
          class="save-btn"
          @click="save"
          :style="[
            `background:${DIYTHEME?.host_bg}`,
            `color:${DIYTHEME?.host_color}`,
          ]"
        >
          确定提交
        </div>
      </hover>
    </div>
  </div>

  <init-load ref="initLoadRef" v-if="initLoading"></init-load>
</template>
<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, getCurrentInstance, onMounted, nextTick } from "vue";
import { getOrderGoodsDetail } from "@/api/order";
import { createOrderRefund } from "@/api/order-refund";
import { uploadCacheImage } from "@/api/common";
import uploadList from "@/components/ui/upload-list/index.vue";
import { Result, ResultError } from "@/types";
import { storeToRefs } from "pinia";
import { useConfig } from "@/store";

const { DIYTHEME } = storeToRefs(useConfig());

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

interface formItemType {
  order_goods_id: number;
  type: number;
  content: string;
  imgs: Array<string>;
  type_desc: string;
}

const formData = ref<formItemType>({
  order_goods_id: 0,
  type: 1,
  content: "",
  imgs: [],
  type_desc: "",
});

const orderGoodsDetail = ref<any>();

const initLoading = ref<boolean>(true);

const toInit = () => {
  getOrderGoodsDetail({
    id: formData.value.order_goods_id,
  })
    .then((res: Result) => {
      orderGoodsDetail.value = res.data;
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const onSelectedType = (type: number) => {
  formData.value.type = type;
};

const imageList = ref<any>([]);

const uploadChange = (res: string[]) => {
  imageList.value = res;
};

const saveLoading = ref<boolean>(false);

const save = () => {
  let _formData = formData.value;
  if (saveLoading.value === true) {
    return false;
  }
  if (_formData.type_desc == '') {
    $utils.errorMsg("请选择申请原因");
    return false;
  }
  if (_formData.content == '') {
    $utils.errorMsg("请输入申请说明");
    return false;
  }
  uni.showLoading({
    title: "正在提交...",
    mask: true,
  });
  saveLoading.value = true;

  // 判断是否需要上传图片
  imageList.value.length > 0
    ? uploadFile(_formData, fromPostCall)
    : fromPostCall(_formData);
};

// form提交执行
const fromPostCall = (_formData: formItemType) => {
  createOrderRefund(_formData)
    .then((res: Result) => {
      uni.hideLoading();
      saveLoading.value = false;
      $utils.successMsg(res.message);
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
      saveLoading.value = false;
    });
};

// 上传图片
const uploadFile = (_formData: formItemType, callBack: Function) => {
  let uploaded: any = [];
  // 文件上传
  let i = 0;
  if (_formData.content !== "") {
    imageList.value.forEach((filePath: string, fileKey: number) => {
      uploadCacheImage(filePath)
        .then((res: Result) => {
          i++;
          uploaded[fileKey] = res.data;
          if (imageList.value.length === i) {
            // 所有文件上传完成
            _formData.imgs = uploaded;
            // 执行回调函数
            callBack && callBack(_formData);
          } else {
            saveLoading.value = false;
          }
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          saveLoading.value = false;
        });
    });
  }
};

const reasonList = ref<any>([
  "商品质量问题",
  "地址问题",
  "已协商一致退款",
  "无理由售后服务",
  "买错了",
]);

const reasonIndex = ref<number>(-1);

const onReasonChange = (e: any) => {
  nextTick(() => {
    reasonIndex.value = Number(e.detail.value);
    formData.value.type_desc = reasonList.value[reasonIndex.value];
  });
};

onLoad((options: any) => {
  formData.value.order_goods_id = options.order_goods_id || 0;
  toInit();
});
</script>
<style>
page {
  background: var(--base-page);
}
</style>
<style scoped>
.goods-detail {
  display: flex;
  justify-content: flex-start;
  background: #fff;
  width: calc(100% - 40rpx);
  margin: 0 auto;
  padding: 20rpx;
}
.goods-detail image {
  width: 160rpx;
  height: 160rpx;
  border-radius: var(--base-radius-default);
  margin-right: 20rpx;
}
.goods-name-bottom {
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: 100%;
  bottom: 0;
  height: 80rpx;
  line-height: 80rpx;
}
.goods-detail-right {
  width: calc(100% - 180rpx);
  position: relative;
}
.goods-sku {
  margin-top: 20rpx;
  padding: 0 10rpx;
  height: 30rpx;
  line-height: 30rpx;
  border-radius: var(--base-radius-default);
  background: #f0f0f0;
  font-size: 24rpx;
}

.service-list {
  display: flex;
  justify-content: flex-start;
  margin: 20rpx 0;
}
.service-item {
  height: 50rpx;
  line-height: 50rpx;
  margin-right: 30rpx;
  padding: 0 30rpx;
  border-radius: var(--base-radius-small);
  background: #f0f0f0;
}
.reason textarea {
  width: 100%;
  margin: 20rpx 0;
  height: 220rpx;
  padding: 12rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: var(--base-radius-default);
  box-sizing: border-box;
}

.cell-main {
  margin: 20rpx auto 0;
  padding: 20rpx;
  background: #fff;
  width: calc(100% - 40rpx);
}
.cell-title {
  height: 60rpx;
  line-height: 60rpx;
}
.bottom-fixed {
  position: fixed;
  width: 100%;
  height: 120rpx;
  z-index: 9999;
  left: 0rpx;
  bottom: 0rpx;
  background: #fff;
}

.save-btn {
  width: calc(100% - 40rpx);
  margin: 25rpx auto;
  text-align: center;
  height: 70rpx;
  line-height: 70rpx;
  color: #fff;
  border-radius: var(--base-radius-default);
}
</style>